import mysql.connector
from mysql.connector import Error

# 替换以下信息为你的数据库信息
db_config = {
    'host': '127.0.0.1',
    'port': '3306',
    'user': 'root',
    'password': 'root',
    'database': 'test'
}


def connect_to_database():
    """
    获取数据库链接
    :return: 数据路链接
    """
    try:
        # python中的 ** 是解包的作用
        connection = mysql.connector.connect(**db_config)

        if connection.is_connected():
            db_info = connection.get_server_info()
            print(f"Connected to MySQL Server version {db_info}")
            cursor = connection.cursor()
            cursor.execute("SELECT DATABASE();")
            record = cursor.fetchone()
            print(f"You're connected to database: {record[0]}")
        return connection
    except Error as e:
        print(f"Error while connecting to MySQL: {e}")
        return None


def execute_query(connection, query):
    """
    用于执行插入、更新、删除等操作的查询。
    :param connection: 链接
    :param query: 查询SQL
    """
    cursor = connection.cursor()
    try:
        cursor.execute(query)
        connection.commit()
        print("Query executed successfully")
    except Error as e:
        print(f"Error: '{e}' occurred")


def fetch_data(connection, query):
    """
    执行 SELECT 查询并返回结果。
    :param connection: 数据库链接
    :param query: 查询SQL
    :return: 查询结果
    """
    cursor = connection.cursor()
    try:
        cursor.execute(query)
        result = cursor.fetchall()
        return result
    except Error as e:
        print(f"Error: '{e}' occurred")
        return None


if __name__ == '__main__':
    connect = connect_to_database()
    if connect is None:
        print("获取数据库链接失败")
    else:
        result = fetch_data(connect, "SELECT * FROM `admin`")
        if result is None or len(result) == 0:
            print("查询结果为空")
        else:
            for row in result:
                # print(row)
                print(row[2])
